package com.fengye.algorithms.leecode;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author fengye
 * @Date 2023/4/8 10:26
 **/
public class ValidSudoku36 {
    public boolean isValidSudoku(char[][] board) {
        Set<Character> rSet = new HashSet<>();
        Set<Character> cSet = new HashSet<>();
        Set<Character>[] sets = new HashSet[board.length];
        for(int i=0;i<9;i++) {
            for(int j=0;j<9;j++) {
                // 处理行
                char r = board[i][j];
                if(Character.isDigit(r)) {
                    if(rSet.contains(r)) {
                        return false;
                    } else {
                        rSet.add(r);
                    }
                }
                // 处理列
                char c = board[j][i];
                if(Character.isDigit(c)) {
                    if(cSet.contains(c)) {
                        return false;
                    } else {
                        cSet.add(c);
                    }
                }
                // 处理方格
                Set<Character> gSet = sets[(j/3) * 3 + i/3];
                if(gSet == null) {
                    gSet = new HashSet<Character>();
                    sets[(j/3) * 3 + i/3] = gSet;
                }
                if(Character.isDigit(c)) {
                    if (gSet.contains(c)) {
                        return false;
                    } else {
                        gSet.add(c);
                    }
                }
            }
            rSet = new HashSet<>();
            cSet = new HashSet<>();
        }

        return true;
    }
}
